package com.collect.cameroon.zhiUtils.zhiFileDownload;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.core.content.ContextCompat;

import com.collect.cameroon.R;
import com.collect.cameroon.zhiGlobal.zhiHandler.ZHIProgressDialogHandler;
import com.collect.cameroon.zhiUtils.ToastUtil;
import com.collect.cameroon.zhiUtils.zhiApkDownload.ApkDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class FileDownloader implements ZHIProgressDialogHandler.ProgressCancelListener{
    private static final int STATE_SUCCESS = -1;
    private static final int STATE_ERROR = -2;

    private Context context;
    private Context applicationContext;
    private String targetUrl;
    private String localFilePath;

    private int fileLength;
    private int currLength;

    private int lastProgress = 0;
    private OnFileDownLoadListener onDownLoadListener;
    private OnFileDownLoadSuccessListener onDownLoadSuccessListener;

    private ApkDialog apkDialog = new ApkDialog();
    private ZHIProgressDialogHandler mZHIProgressDialogHandler;

    private static List<String> downloadManager = new ArrayList<>();

    public FileDownloader(Context context, String targetUrl, String localFilePath) {
        this.context = context;
        this.targetUrl = targetUrl;
        this.localFilePath = localFilePath;
        this.applicationContext = context.getApplicationContext();
        this.apkDialog = new ApkDialog();
    }

    public boolean checkPermission(){
        List<String> permissions  = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);

        for (String permission : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(context, permission)) {
                return false;
            }
        }

        return true;
    }

    public void downloadFile() {
        if (checkPermission()){
            try {
                init();
                okHttpBeginDownload();
            }
            catch (Exception ex){
                try {
                    ToastUtil.l(context.getResources().getString(R.string.download_error));
                }
                catch (Exception ex2){
                }
            }
        }
        else{
            try {
                ToastUtil.l(context.getResources().getString(R.string.download_error));
            }
            catch (Exception e){
            }
        }
    }

    private void init(){
        this.onDownLoadListener = new OnFileDownLoadListener() {
            @Override
            public void onProgress(int progress) {
                try{
                    //apkDialog.showDownloadDialog(context, progress);
                }catch (Exception ex){

                }
            }

            @Override
            public void onSuccess() {
                try{
                    apkDialog.dismissDownloadDialog();
                }catch (Exception ex){

                }
                //下载完成
            }

            @Override
            public void onError() {
                try{
                    apkDialog.dismissDownloadDialog();
                }catch (Exception ex){

                }
                ToastUtil.l(context.getResources().getString(R.string.download_failed));
            }
        };
    }

    private void okHttpBeginDownload(){
        if(mZHIProgressDialogHandler == null){
            mZHIProgressDialogHandler = new ZHIProgressDialogHandler(context, this, false);
        }

        showProgressDialog();

        Executors.newCachedThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client =new OkHttpClient.Builder().build();
                    Request request = new Request.Builder().url(targetUrl)
                            .get().build();
                    Call call =client.newCall(request);
                    Response response =call.execute();

                    ResponseBody body = response.body();
                    InputStream inputStream = body.byteStream();
                    final long lengh = body.contentLength();
                    System.out.println("文件大小"+ lengh);

                    File file1 = new File(localFilePath);
                    FileOutputStream outputStream = new FileOutputStream(file1);
                    int lien=0;
                    int losing=0;
                    byte[] bytes=new byte[1024];
                    while ((lien = inputStream.read(bytes)) != -1){
                        outputStream.write(bytes,0,lien);

                        losing+=lien;
                        final float i=losing*1.0f/lengh;
                        System.out.println("下载进度"+i);

                        int progress =(int) (i*100);
                        handler.sendEmptyMessage(progress);
                    }

                    outputStream.flush();
                    inputStream.close();
                    outputStream.close();

                    onDownLoadListener.onSuccess();
                    onDownLoadSuccessListener.onSuccess();
                    dismissProgressDialog();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void setOnFileDownLoadListener(OnFileDownLoadListener onDownLoadListener) {
        this.onDownLoadListener = onDownLoadListener;
    }

    public void setOnDownLoadSuccessListener(OnFileDownLoadSuccessListener onDownLoadSuccessListener){
        this.onDownLoadSuccessListener = onDownLoadSuccessListener;
    }

    public interface OnFileDownLoadListener {
        void onProgress(int progress);

        void onSuccess();

        void onError();
    }

    public interface OnFileDownLoadSuccessListener {
        void onSuccess();
    }


    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (onDownLoadListener != null) {
                switch (msg.what) {
                    case STATE_SUCCESS:
                        onDownLoadListener.onSuccess();
                        onDownLoadSuccessListener.onSuccess();
                        break;
                    case STATE_ERROR:
                        onDownLoadListener.onError();
                        if (msg.obj != null && msg.obj instanceof String) {
                            //ToastUtil.l((String)msg.obj);
                        }
                        break;
                    default:
                        if (lastProgress != msg.what) {
                            lastProgress = msg.what;
                            onDownLoadListener.onProgress(msg.what);
                        }
                        break;
                }
            }
        }
    };


    @Override
    public void onCancelProgress() {
    }

    private void showProgressDialog() {
        if (mZHIProgressDialogHandler != null) {
            mZHIProgressDialogHandler.show();
        }
    }

    private void dismissProgressDialog() {
        if (mZHIProgressDialogHandler != null) {
            mZHIProgressDialogHandler.hide();
            mZHIProgressDialogHandler = null;
        }
    }
}
